package com.commerceerp.system.service;

import com.commerceerp.system.api.amazon.client.MwsUtl;
import com.commerceerp.system.api.amazon.orders._2013_09_01.MarketplaceWebServiceOrdersAsyncClient;
import com.commerceerp.system.api.amazon.orders._2013_09_01.MarketplaceWebServiceOrdersClient;
import com.commerceerp.system.api.amazon.orders._2013_09_01.MarketplaceWebServiceOrdersConfig;
import com.commerceerp.system.api.amazon.orders._2013_09_01.model.*;
import com.commerceerp.system.api.amazon.orders._2013_09_01.samples.ListOrderItemsSample;
import com.commerceerp.system.api.amazon.orders._2013_09_01.samples.ListOrdersSample;
import com.commerceerp.system.api.amazon.product.MarketplaceWebServiceProductsAsyncClient;
import com.commerceerp.system.api.amazon.product.MarketplaceWebServiceProductsClient;
import com.commerceerp.system.api.amazon.product.MarketplaceWebServiceProductsConfig;
import com.commerceerp.system.api.amazon.product.model.GetMatchingProductForIdRequest;
import com.commerceerp.system.api.amazon.product.model.GetMatchingProductForIdResponse;
import com.commerceerp.system.api.amazon.product.model.IdListType;
import com.commerceerp.system.api.amazon.product.samples.GetMatchingProductForIdSample;
import com.commerceerp.system.api.amazon.product.samples.MarketplaceWebServiceProductsSampleConfig;
import com.commerceerp.system.entity.*;
import com.commerceerp.system.mapper.GoodMapper;
import com.commerceerp.system.mapper.OrderMapper;
import com.commerceerp.system.mapper.ShopMapper;
import com.commerceerp.system.util.ApiResult;
import com.commerceerp.system.util.StringUtils;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.datatype.XMLGregorianCalendar;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2018/7/20 0020.
 */
@Service
public class AmazonService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodMapper goodMapper;


    public ApiResult getOrder(String userId, String date) {
        int year = Integer.valueOf(date.substring(0, 4));
        int month = Integer.valueOf(date.substring(5, 7));
        int day = Integer.valueOf(date.substring(8, 10));
        List<ShopAmazon> shopAmazons = shopMapper.getShopAmazons(userId);
        if (shopAmazons == null || shopAmazons.size() == 0) {
            logger.info("");
        }
        for (ShopAmazon shopAmazon : shopAmazons) {
            try {
                String serviceURL = shopAmazon.getEndpoint();
                String accessKey = shopAmazon.getAwsAccessKeyId();
                String secretKey = shopAmazon.getSecretKey();
                String appName = "erp";
                String appVersion = "2";
                String sellerId = shopAmazon.getMerchantId();

                MarketplaceWebServiceOrdersConfig config = new MarketplaceWebServiceOrdersConfig();
                config.setServiceURL(serviceURL);
                MarketplaceWebServiceOrdersClient client = new MarketplaceWebServiceOrdersAsyncClient(accessKey, secretKey,
                        appName, appVersion, config, null);

                ListOrdersRequest request = new ListOrdersRequest();
                request.setSellerId(sellerId);
                XMLGregorianCalendar createdAfter = MwsUtl.getDTF().newXMLGregorianCalendar();

                createdAfter.setYear(year);
                createdAfter.setMonth(month);
                createdAfter.setDay(day);
                createdAfter.setTime(0, 0, 0);
                request.setCreatedAfter(createdAfter);
                List<String> marketplaceId = new ArrayList<String>();
                marketplaceId.add(shopAmazon.getMarketplaceId());
                request.setMarketplaceId(marketplaceId);
                Integer maxResultsPerPage = 100;
                request.setMaxResultsPerPage(maxResultsPerPage);
                List<String> tfmShipmentStatus = new ArrayList<String>();
                request.setTFMShipmentStatus(tfmShipmentStatus);
                ListOrdersResponse response = ListOrdersSample.invokeListOrders(client, request);
                List<Order> orders = response.getListOrdersResult().getOrders();
                for (Order o : orders) {
                    try {
                        OrderVo orderInfo = new OrderVo();
                        orderInfo.setOrderStoreId(shopAmazon.getId());
                        orderInfo.setShopUserId(shopAmazon.getShopUserId());
                        orderInfo.setOrderChannel("2");
                        if (o.getLastUpdateDate() != null) {
                            String lastUpdateDate = o.getPurchaseDate().toString();
                            lastUpdateDate = lastUpdateDate.replace("T", " ").replace("Z", "");
                            orderInfo.setUpdTime(lastUpdateDate);
                        }
                        if (o.getPurchaseDate() != null) {
                            String orderDownTime = o.getPurchaseDate().toString();
                            orderDownTime = orderDownTime.replace("T", " ").replace("Z", "");
                            orderInfo.setOrderDownTime(orderDownTime);
                        }
                        if (o.getOrderTotal() != null && StringUtils.isNotEmpty(o.getOrderTotal().getAmount())) {
                            //订单的总价值
                            orderInfo.setOrderMoney(o.getOrderTotal().getAmount() + o.getOrderTotal().getCurrencyCode());
                            if (!StringUtils.equals(o.getOrderTotal().getCurrencyCode(), "USD")) {
                                //兑换成人民币
                                orderInfo.setOrderMoneyCny(shopMapper.getMoneyUSD(o.getOrderTotal().getAmount(), o.getOrderTotal().getCurrencyCode()));
                            } else {
                                orderInfo.setOrderMoneyCny(o.getOrderTotal().getAmount());
                            }
                        }
                        if (o.getBuyerName() != null) {
                            //买家名称
                            orderInfo.setOrderBuyerId(o.getBuyerName());
                        }

                        //订单id
                        orderInfo.setOrderId(o.getAmazonOrderId());
//                        PendingAvailability 只有预订订单才有此状态。订单已生成，但是付款未授权且商品的发售日期是将来的某一天。订单尚不能进行发货。请注意：仅在日本 (JP)，Preorder 才可能是一个 OrderType 值。
//                        Pending 订单已生成，但是付款未授权。订单尚不能进行发货。请注意：对于 OrderType = Standard 的订单，初始的订单状态是 Pending。对于 OrderType = Preorder 的订单（仅适用于 JP），初始的订单状态是 PendingAvailability，当进入付款授权流程时，订单状态将变为 Pending。
//                        Unshipped 付款已经过授权，订单已准备好进行发货，但订单中商品尚未发运。
//                        PartiallyShipped 订单中的一个或多个（但并非全部）商品已经发货。
//                        Shipped 订单中的所有商品均已发货。
//                        InvoiceUnconfirmed 订单中的所有商品均已发货。但是卖家还没有向亚马逊确认已经向买家寄出发票。请注意：此参数仅适用于中国地区。
//                        Canceled 订单已取消。
//                        Unfulfillable 订单无法进行配送。该状态仅适用于通过亚马逊零售网站之外的渠道下达但由亚马逊进行配送的订单。

                        String orderStatus = o.getOrderStatus();//1:待审核,2:待处理,3:待发货,4:发货成功,5:发货失败,6:取消,7:完成
                        String status = "";
                        if ("PendingAvailability".equalsIgnoreCase(orderStatus)) {
                            status = "1";
                        } else if ("Pending".equalsIgnoreCase(orderStatus)) {
                            status = "2";
                        } else if ("Unshipped".equalsIgnoreCase(orderStatus)) {
                            status = "3";
                        } else if ("PartiallyShipped".equalsIgnoreCase(orderStatus) || "Shipped".equalsIgnoreCase(orderStatus)
                                || "InvoiceUnconfirmed".equalsIgnoreCase(orderStatus)) {
                            status = "4";
                        } else if ("Canceled".equalsIgnoreCase(orderStatus)) {
                            status = "6";
                        } else if ("Unfulfillable".equalsIgnoreCase(orderStatus)) {
                            status = "5";
                        }
                        orderInfo.setOrderStatus(status);

                        if (StringUtils.isNotEmpty(o.getBuyerName())) {//买家
                            orderInfo.setOrderBuyerId(o.getBuyerName());
                        }

                        Address address = o.getShippingAddress();
                        if (address != null) {
                            if (StringUtils.isNotEmpty(address.getPhone())) {//收件人号码
                                orderInfo.setAddressPhone(address.getPhone());
                            }
                            if (StringUtils.isNotEmpty(address.getCity())) {//收件城市
                                orderInfo.setAddressCity(address.getCity());
                            }
                            if (StringUtils.isNotEmpty(address.getStateOrRegion())) {//收件地区
                                orderInfo.setAddressProvince(address.getStateOrRegion());
                            }
                            if (StringUtils.isNotEmpty(address.getName())) {//收件人
                                orderInfo.setAddressRecipients(address.getName());
                            }
                            if (StringUtils.isNotEmpty(address.getCounty())) {//收件国家
                                orderInfo.setAddressCountry(address.getCounty());
                            }
                            if (StringUtils.isNotEmpty(address.getPostalCode())) {//邮编
                                orderInfo.setAddressPostcode(address.getPostalCode());
                            }
                            if (StringUtils.isNotEmpty(address.getAddressLine1())) {//收件地址
                                orderInfo.setAddressLocationA(address.getAddressLine1());
                            }
                            if (StringUtils.isNotEmpty(address.getAddressLine2())) {
                                String streetAddress2 = address.getAddressLine2();//收件地址2
                                orderInfo.setAddressLocationB(streetAddress2);
                            }
                        }
                        //检索订单id
                        String id = orderMapper.getOrderIdId(orderInfo.getOrderId());
                        if (StringUtils.isEmpty(id)) {//新增订单
                            StringUtils.getOrderSerialNumber(orderInfo);
                            orderInfo.insert();
                            orderMapper.insert(orderInfo);

                            saveOrderDetail(sellerId, client, accessKey, secretKey, o.getAmazonOrderId(), shopAmazon.getMarketplaceId(), orderInfo.getId());
                        } else {//修改订单
                            orderInfo.setId(id);
                            orderMapper.update(orderInfo);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return new ApiResult(200, "同步完成");
    }

    public void saveOrderDetail(String sellerId, MarketplaceWebServiceOrdersClient client, String accessKey,
                                String secretKey, String amazonOrderId, String marketplaceId, String orderId) {
        //商品信息
        ListOrderItemsRequest product = new ListOrderItemsRequest();
        product.setSellerId(sellerId);
        product.setAmazonOrderId(amazonOrderId);
        try {
            List<OrderItem> items = ListOrderItemsSample.invokeListOrderItems(client, product).getListOrderItemsResult().getOrderItems();
            if (items != null && items.size() > 0) {
                List<OrderDetailVo> detailVos = Lists.newArrayList();
                MarketplaceWebServiceProductsClient pclient = MarketplaceWebServiceProductsSampleConfig.getClient(accessKey, secretKey);
                GetMatchingProductForIdRequest pdetail = new GetMatchingProductForIdRequest();
                pdetail.setSellerId(sellerId);
                pdetail.setMarketplaceId(marketplaceId);
                String idType = "SellerSKU";
                pdetail.setIdType(idType);

                for (OrderItem orderItem : items) {
                    OrderDetailVo orderDetailVo = new OrderDetailVo();
                    GoodInfo goodInfo = new GoodInfo();
                    goodInfo.setGoodPlatformType("2");
                    goodInfo.setGoodPlatformName(orderItem.getTitle());
                    goodInfo.setGoodPlatformId(orderItem.getOrderItemId());
                    List<String> ids = new ArrayList<>();
                    ids.add(orderItem.getSellerSKU());
                    orderDetailVo.setOrderSku(orderItem.getSellerSKU());//sku
                    goodInfo.setGoodPlatformSku(orderItem.getSellerSKU());
                    orderDetailVo.setOrderGoodNumber(orderItem.getProductInfo().getNumberOfItems());//数量
                    Money money = orderItem.getItemPrice();
                    if (money != null) {
                        orderDetailVo.setOrderGoodPrice(orderItem.getItemPrice().getAmount() + orderItem.getItemPrice().getCurrencyCode());//单价
                        goodInfo.setGoodPurchasePrice(Double.valueOf(orderItem.getItemPrice().getAmount()));
                    }
                    orderDetailVo.setOrderGoodId(orderItem.getOrderItemId());//产品id
                    goodInfo.setGoodPlatformId(orderItem.getOrderItemId());

                    orderDetailVo.setOrderId(orderId);
                    orderDetailVo.insert();

                    IdListType idList = new IdListType();
                    idList.setId(ids);
                    pdetail.setIdList(idList);
                    try {
                        // Make the call.
                        GetMatchingProductForIdResponse result = GetMatchingProductForIdSample.invokeGetMatchingProductForId(pclient, pdetail);
                        String responseXml = result.toXML();
                        if (responseXml.indexOf("<ns2:URL>") > 0) {
                            String url = responseXml.substring(responseXml.indexOf("<ns2:URL>") + 9, responseXml.indexOf("</ns2:URL>"));
                            orderDetailVo.setOrderImageUrl(url);
                            goodInfo.setGoodPicPath(url);
                        }
                        if (responseXml.indexOf("<ASIN>") > 0) {
                            String asin = responseXml.substring(responseXml.indexOf("<ASIN>") + 6, responseXml.indexOf("</ASIN>"));
                            goodInfo.setGoodUrl("https://www.amazon.com/gp/product/" + asin);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //根据平台商品id，获取本系统商品ID
                    String goodId = goodMapper.getGoodIdByPlatformId(goodInfo.getGoodPlatformId());
                    if (StringUtils.isEmpty(goodId)) {
                        goodInfo.setGoodId(StringUtils.getUUID());
                        goodMapper.saveNewSystemGood(goodInfo);
                    }

                    detailVos.add(orderDetailVo);
                }
                orderMapper.insertOrderDetail(detailVos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getImgUrl() {

        // Create a request.
        List<SkuVo> skus = orderMapper.getOrderSku();
        for (SkuVo sku : skus) {
            MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig();
            config.setServiceURL(sku.getEndpoint());
            // Set other client connection configurations here.
            MarketplaceWebServiceProductsAsyncClient client = new MarketplaceWebServiceProductsAsyncClient(sku.getAwsAccessKeyId(), sku.getSecretKey(),
                    "erp", "2", config, null);
            GetMatchingProductForIdRequest request = new GetMatchingProductForIdRequest();
            String sellerId = sku.getMerchantId();
            request.setSellerId(sellerId);
            String marketplaceId = sku.getMarketplaceId();
            request.setMarketplaceId(marketplaceId);
            String idType = "SellerSKU";
            request.setIdType(idType);
            List<String> id = new ArrayList<>();
            id.add(sku.getOrderSku());
            IdListType idList = new IdListType();
            idList.setId(id);
            request.setIdList(idList);
            try {
                // Make the call.
                GetMatchingProductForIdResponse result = GetMatchingProductForIdSample.invokeGetMatchingProductForId(client, request);
                String responseXml = result.toXML();
                if (responseXml.indexOf("<ns2:URL>") > 0) {
                    String url = responseXml.substring(responseXml.indexOf("<ns2:URL>") + 9, responseXml.indexOf("</ns2:URL>"));
                    orderMapper.updOrderImg(sku.getOrderSku(), url);
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }

    }

}
